import axios from "axios"; // 引入axios
import { Message } from "element-ui";
import store  from "@/store/index.js";
import context from "@/main.js";
// import router from "@/router/index";
import { httpMessage, codeMessage } from "./common.js";
// import { dataTrim } from "./utils";

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 30000,
});

// 加载中
let acitveAxios = 0;
let timer;
const showLoading = () => {
  acitveAxios++;
  if (timer) {
    clearTimeout(timer);
  }
  timer = setTimeout(() => {
    if (acitveAxios > 0) {
      context.$bus.emit("showLoading");
    }
  }, 400);
};

// 关闭加载
const closeLoading = () => {
  acitveAxios--;
  if (acitveAxios <= 0) {
    clearTimeout(timer);
    context.$bus.emit("closeLoading");
  }
};

// 服务器状态判断，比如网络异常等
const err = (error) => {
  closeLoading();
  if (
    error.toString().indexOf("Error: timeout") > -1 ||
    error.toString().indexOf("Error: Network") > -1
  ) {
    Message({
      showClose: true,
      message: "网络请求超时, 请稍后刷新重试~",
      type: "error",
    });
  }
  if (error?.response) {
    Message({
      showClose: true,
      message:
        codeMessage[error.response?.status] ||
        error.response?.msg ||
        "网络异常，请稍后再试",
      type: "error",
    });
  }

  return Promise.reject(error);
};

// 业务API拦截判断，如登陆态等
async function apiError(data) {
  const { code, msg } = data;
  Message({
    showClose: true,
    message: codeMessage[code] || msg,
    type: "error",
  });
  switch (code) {
    case 90401:
      await store.dispatch("user/LoginOut", {}, { root: true });
      break;
    case 90407:
      await store.dispatch("user/LoginOut", {}, { root: true });
      break;
    case 10108: //角色被修改了，需要重新获取角色列表
      await store.dispatch("user/getRolesList", {}, { root: true });
      break;
    default:
      break;
  }

  return Promise.reject(data);
}

//http request 拦截器
service.interceptors.request.use((config) => {
  if (!config.donNotShowLoading) {
    showLoading();
  }
  // dataTrim(config.data);
  config.withCredentials = true;
  const token = store.getters["user/token"];
  // const user = store.getters["user/userInfo"];
  if (config.headers["Content-Type"] !== "multipart/form-data") {
    config.data = JSON.stringify(config.data);
  }
  // console.log("  config.data", config.data);
  config.withCredentials = true;
  config.headers = {
    "Content-Type": "application/json",
    "x-token": token,
    ...config.headers,
  };
  // 如果是本地开发，则不验证Referer
  // if(process.env.NODE_ENV === "development") {
  //   config.headers["Referer"] = ""
  // }
  // 如果是登陆接口，则不传x-token
  if (config.url == "/user/login") {
    delete config.headers["x-token"];
  }

  // console.log('this.$route.',config)
  return config;
}, err);

//http response 拦截器
service.interceptors.response.use(async (response) => {
  // console.log("response", response);
  closeLoading();
  if (response.headers["new-token"]) {
    store.commit("user/setToken", response.headers["new-token"]);
  }

  const { code } = response.data;
  if (response["headers"]["content-type"] === "application/octet-stream") {
    return {
      code: 0,
      ...response,
    };
  } else if (code !== 0) {
    // console.log(code);
    return apiError(response.data);
  }
  return response.data;
}, err);

export default service;
